import '../App.css'
import { TabBar, Toast } from 'antd-mobile'
import right from '../assets/箭头-右.png'
import add from '../assets/add.png'
import big from '../assets/xiao.png'  // 已添加状态的图标
import { path } from '../config/index.ts'
import shopping from '../assets/shopping.png'
import { useState, useEffect } from 'react'
import { home, shoppingList, shoppingAdd, shoppingEdit } from '../api/index.ts'
import { useNavigate, useLocation } from 'react-router-dom'
import {
    AppOutline,
    UnorderedListOutline,
    UserOutline,
} from 'antd-mobile-icons'

export default function Mine() {
    const [data, setData] = useState<any>(null);
    const [cartData, setCartData] = useState<any[]>([]); // 存储购物车数据
    const [addedCommodities, setAddedCommodities] = useState<Set<string>>(new Set()); // 跟踪已添加的商品ID
    const userId = localStorage.getItem('uid');
    const navigate = useNavigate();
    const location = useLocation();

    useEffect(() => {
        const fetchHomeData = async () => {
            try {
                const res = await home({});
                console.log('接口返回:', res.data);
                setData(res.data);
            } catch (error) {
                console.error('home接口请求失败:', error);
            }
        };

        // 初始化时获取购物车数据
        const initCartData = async () => {
            if (userId) {
                await fetchCartList(userId);
            }
        };

        fetchHomeData();
        initCartData();
    }, [userId]);

    // 重新请求购物车列表的函数
    const fetchCartList = async (userId: string) => {
        try {
            const cartListRes = await shoppingList({ id: userId });
            const cartList = cartListRes.data || [];
            setCartData(cartList);

            // 将购物车中已存在的商品ID添加到集合中
            const addedIds = new Set<string>();
            cartList.forEach((item: any) => {
                if (item.commodity && item.commodity.length > 0) {
                    addedIds.add(item.commodity[0].id);
                }
            });

            setAddedCommodities(addedIds);
        } catch (error) {
            console.error('获取购物车列表失败:', error);
            Toast.show('获取购物车列表失败');
        }
    };

    // 添加购物车方法
    const handleAddToCart = async (commodityId: string) => {
        // 从本地存储获取user_id
        const userId = localStorage.getItem('uid');
        if (!userId) {
            console.log('用户ID获取失败，请重新登录');
            Toast.show('用户ID获取失败，请重新登录');
            return;
        }

        try {
            // 查找购物车中是否已存在该商品
            const existingCartItem = cartData.find((item: any) =>
                item.commodity && item.commodity.some((comm: any) => comm.id === commodityId)
            );

            if (existingCartItem) {
                // 存在，调用编辑接口，数量加一
                const editRes = await shoppingEdit({
                    id: existingCartItem.id, // 购物车id
                    num: (parseInt(existingCartItem.num) + 1).toString() // 数量加一
                });
                if (editRes.code === 1) {
                    console.log('编辑购物车成功');
                    Toast.show('购物车商品数量加一');
                    // 重新请求购物车列表
                    await fetchCartList(userId);
                } else {
                    console.error(`编辑购物车失败：${editRes.message || '未知错误'}`);
                    Toast.show('编辑购物车失败');
                }
            } else {
                // 不存在，调用新增接口
                const addRes = await shoppingAdd({
                    user_id: userId,
                    commodity_id: commodityId,
                    num: '1'
                });
                console.log('shoppingAdd 接口返回', addRes);
                if (addRes.code === 1) {
                    console.log('添加购物车成功');
                    Toast.show('已添加到购物车');
                    // 重新请求购物车列表
                    await fetchCartList(userId);
                } else {
                    console.error(`添加购物车失败：${addRes.message || '未知错误'}`);
                    Toast.show('添加购物车失败');
                }
            }
        } catch (error) {
            console.error('购物车操作请求失败:', error);
            Toast.show('购物车操作失败，请稍后重试');
        }
    };

    // 跳转到商品详情页
    const navigateToDetail = (product: any, productId: string) => {
        sessionStorage.setItem('dataList', JSON.stringify(product));
        navigate(`/xiangqing/${productId}`);
    };

    const tabs = [
        {
            key: '/',
            title: '首页',
            icon: <AppOutline />,
            onClick: () => navigate('/')
        },
        {
            key: '/category',
            title: '分类',
            icon: <UnorderedListOutline />,
            onClick: () => navigate('/category')
        },
        {
            key: '/cart',
            title: '购物车',
            icon: (active: boolean) => <img src={active ? shopping : shopping} alt="" style={{ width: '24px', height: '24px' }} />,
            onClick: () => navigate('/cart')
        },
        {
            key: '/mine',
            title: '我的',
            icon: <UserOutline />,
            onClick: () => navigate('/mine')
        },
    ]

    // 根据当前路径确定activeKey
    const activeKey = tabs.find(tab => location.pathname === tab.key)?.key || '/';

    return (
        <div>
            {/* 顶部 */}
            <div className='image'>
                <div className='h10'></div>
                <div className='positionRight'>
                    <img src="https://img.xiaopiu.com/userImages/img17140018ac50ac908.png" alt="设置图标" className='w20' />
                </div>
                {/* 头像 */}
                <div className='dis'>
                    <img src="https://img.xiaopiu.com/userImages/img326164da748e08.jpeg" alt="用户头像" className='imaged' />
                    <div className='Dis'>
                        <span style={{ fontSize: '15px', marginBottom: '5px' }}>顺颂时祺</span>
                        <div className='id'>
                            ID：1008686
                        </div>
                    </div>
                </div>
                {/* 收益 */}
                <div className='m30'>
                    <div className='dis-bottom'>
                        <div>
                            ￥<span style={{ fontSize: '19px' }}>1234.56</span>
                        </div>
                        <div>
                            余额(元)
                        </div>
                    </div>
                    <div className='dis-bottom'>
                        <div>
                            ￥<span style={{ fontSize: '19px' }}>3456</span>
                        </div>
                        <div>
                            总收益(元)
                        </div>
                    </div>
                    <div className='dis-bottom'>
                        <div>
                            ￥<span style={{ fontSize: '19px' }}>789</span>
                        </div>
                        <div>
                            可用收益(元)
                        </div>
                    </div>
                </div>
            </div>
            <div style={{ height: '30px' }}></div>
            {/* 我的订单 */}
            <div className='white w96'>
                <div className='me'>
                    <div style={{ fontSize: '15px' }}>我的订单</div>
                    <div style={{ display: 'flex', alignItems: 'center' }} onClick={() => navigate('/quanbu')}>
                        <span>全部订单</span>
                        <img src={right} alt="右箭头" className='icon' />
                    </div>
                </div>
                <div style={{ display: 'flex', marginTop: '20px' }}>
                    <div className='topBott'>
                        <img src="https://img.xiaopiu.com/userImages/img17140218ac5183688.png" alt="待付款" className='width' />
                        <span>待付款</span>
                    </div>
                    <div className='topBott'>
                        <img src="https://img.xiaopiu.com/userImages/img17140518ac5219110.png" alt="待收货" className='width' />
                        <span>待收货</span>
                    </div>
                    <div className='topBott'>
                        <img src="https://img.xiaopiu.com/userImages/img17140518ac5219110.png" alt="待评价" className='width' />
                        <span>待评价</span>
                    </div>
                    <div className='topBott'>
                        <img src="https://img.xiaopiu.com/userImages/img17140718ac5222198.png" alt="已完成" className='width' />
                        <span>已完成</span>
                    </div>
                    <div className='topBott'>
                        <img src="https://img.xiaopiu.com/userImages/img17140818ac5223908.png" alt="退换货" className='width' />
                        <span>退换货</span>
                    </div>
                </div>
            </div>
            {/* 我的服务 */}
            <div className='white w96'>
                <div className='me'>
                    <div style={{ fontSize: '15px' }}>我的服务</div>
                </div>
                <div style={{ display: 'flex', marginTop: '20px' }}>
                    <div className='topBott w25'>
                        <img src="https://img.xiaopiu.com/userImages/img17169918ac682a7b0.png" alt="我的钱包" className='width' />
                        <span>我的钱包</span>
                    </div>
                    <div className='topBott w25'>
                        <img src="https://img.xiaopiu.com/userImages/img17170418ac6836b00.png" alt="分销中心" className='width' />
                        <span>分销中心</span>
                    </div>
                    <div className='topBott w25'>
                        <img src="https://img.xiaopiu.com/userImages/img17170518ac68395f8.png" alt="收货地址" className='width' />
                        <span>收货地址</span>
                    </div>
                    <div className='topBott w25'>
                        <img src="https://img.xiaopiu.com/userImages/img17499418acc4c92c8.png" alt="邀请好友" className='width' />
                        <span>邀请好友</span>
                    </div>
                </div>
            </div>
            {/* 猜你喜欢 */}
            <div className='w100'>
                <img src="https://img.xiaopiu.com/userImages/img17176718ac69291e8.png" alt="" className='width' />
                <span>猜你喜欢</span>
                <img src="https://img.xiaopiu.com/userImages/img17177018ac6930b00.png" alt="" className='w20' />
            </div>
            <div className="column">
                {data?.commodity?.map((item, index) => (
                    <div className="list_box" key={index}>
                        <div className="list_item" onClick={() => navigateToDetail(item, item.id)}>
                            <img
                                src={path + item.image || 'https://img.xiaopiu.com/userImages/img17095018ac1206f78.jpg'}
                                alt={item.title}
                            />
                            <div className='m7'>
                                {item.title}
                            </div>
                        </div>
                        <div className="icon_img">
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <span className='red'>￥{item.price}</span>
                            </div>
                            <div>
                                {/* 根据商品是否已添加，显示不同图标并绑定添加事件 */}
                                <img
                                    src={addedCommodities.has(item.id) ? big : add}
                                    alt={addedCommodities.has(item.id) ? "已添加" : "添加"}
                                    className='width'
                                    onClick={() => handleAddToCart(item.id)}
                                />
                            </div>
                        </div>
                    </div>
                ))}
            </div>
            <div style={{ height: '80px' }}></div>
            {/* 底部导航栏 */}
            <TabBar activeKey={activeKey} onChange={(key) => {
                const tab = tabs.find(tab => tab.key === key);
                if (tab) {
                    tab.onClick();
                }
            }}>
                {tabs.map(item => (
                    <TabBar.Item
                        key={item.key}
                        icon={item.icon}
                        title={item.title}
                        onClick={item.onClick}
                    />
                ))}
            </TabBar>
        </div>
    )
}
